package com.lee.post;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * User:liwei
 * Date:2017/8/31
 * Time:15:54
 */
public class HttpClientTool {
    /**
     * 线程安全的HTTP CLient端
     */
    private static CloseableHttpClient httpClient = null;

    /**
     * 此参数适当的加大设置，当对方服务器反应很慢时，会有超时报出;
     */
    private static final int requestTimeOut = 100 * 1000;

    /**
     * 初始化HTTPClientPoll;
     */
    static {

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(1000);
        cm.setDefaultMaxPerRoute(50);
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(requestTimeOut)
                .setSocketTimeout(10 * 1000).setConnectTimeout(10 * 1000).build();

        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setBufferSize(4128)
                .build();

        httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                .setDefaultConnectionConfig(connectionConfig)
                .setConnectionManager(cm)
                .setConnectionTimeToLive(1000, TimeUnit.SECONDS).build();

    }

    /**
     * 发起post请求
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String,String> params) throws Exception {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            NameValuePair nvp = new BasicNameValuePair(key, params.get(key));
            nvps.add(nvp);
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=utf-8>");
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        HttpContext context = HttpClientContext.create();
        CloseableHttpResponse response = httpClient.execute(httpPost, context);
        if (response != null)
            return getResult(response);
        return null;
    }

    /**
     *
     * @param response
     * @return
     * @throws ParseException
     * @throws IOException
     */
    private static String getResult(CloseableHttpResponse response) throws Exception {
        try {
            HttpEntity entity = response.getEntity();
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK && entity != null) {
                String html = EntityUtils.toString(entity, "utf-8");
                return html;
            } else {
                throw new Exception("返回服务器状态不正确:" + status);
            }
        } finally {
            response.close();
        }
    }
}
